<template>
	<view class="commutation">
		<view class="middle">
			<scroll-view class="scroll-view" :scroll-y="true" :scroll-top="scrollTop" :scroll-with-animation="false">
				<view id="scroll-view-content">
					<template v-if="list.length !== 0">
						<template v-for="(item,index) in list">
							<view class="box">
								<view class="left" v-if="!item.isRight">
									<view class="left_image">
										<avatar :name="sendUser.originators" :size="'big'" />
										<!-- <image src="https://file.mjcelaine.top/newimages/initImgUrl.jpg" mode="">
										</image> -->
									</view>
									<view class="left_text" v-html="initalEmoji(item.msg)"></view>
								</view>
								<view class="right" v-else>
									<view class="right_text" v-html="initalEmoji(item.msg)"></view>
									<view class="right_image">
										<avatar :name="userName" :size="'big'" />
									</view>
								</view>
							</view>
						</template>
					</template>

				</view>
			</scroll-view>
		</view>

		<view class="bottom">
			<view class="bottom_top">
				<view class="bottom_top_left">
					<uni-easyinput v-model="text" :inputBorder="false" :clearable="false" type="text" />
				</view>
				<view class="bottom_top_right">
					<view class="iconfontbody">
						<view class="iconfontbody_xiaolian" @click.native="toggle">
							<image src="../../static/xiaolian.png" mode=""></image>
						</view>
						<view class="iconfontbody_send" @click.native="send">
							<image src="../../static/send.png" mode=""></image>
						</view>
					</view>
				</view>
			</view>
		</view>
		<uni-popup ref="popup" type="bottom">
			<emotion @emotion="handleemotion" @closePopup="closePopup" />
		</uni-popup>
	</view>
</template>

<script>
	import avatar from '@/components/common/avatar/index.vue'
	import {
		text2pic
	} from '@/components/emotin/utils.js'
	import emotion from '@/components/emotin/index.vue'
	// import io from '@hyoga/uni-socket.io';

	export default {
		components: {
			avatar,
			emotion
		},
		data() {
			return {
				userName: '',
				userId: 0,
				scrollViewHeight: 0,
				scrollTop: 0,
				text: '',
				sendUser: {
					originators: '',
					captionId: 0,
					teamId: 0,
				},
				list: []
			}
		},
		components: {
			emotion
		},
		methods: {
			async getUser() {
				try {
					const res = await this.$mjcrequest.request({
						url: this.$api.getUser,
						method: 'GET',
						header: this.$aplsjsonheader,
					})
					this.$binduserInfo(res)
					console.log(this.$userInfo, 269);
				} catch (e) {

					this.$errMessageToast(e)
				}
			},
			initalEmoji(item) {
				const txt = text2pic(item)
				return txt
			},
			closePopup() {
				console.log('closePopup');
				this.$refs.popup.close()
			},
			handleemotion(txt) {

				this.text += txt

			},
			toggle() {
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open()
			},
			scrollToBottom() {
				uni.createSelectorQuery().in(this).select('#scroll-view-content').boundingClientRect((res) => {
					let top = res.height - this.scrollViewHeight;
					console.log(top, 'top');
					if (top > 0) {
						this.scrollTop = top + 100;
					}
				}).exec()
			},
			async send() {
				if (this.text == '') {

					return
				}
				try {
					const data = {
						toId: this.sendUser.captionId,
						msg: this.text
					}
					const res = await this.$mjcrequest.request({
						url: this.$api.sendChat,
						header: this.$aplsjsonheader,
						data: JSON.stringify(data)
					})
					this.list.push({
						isRight: true,
						msg: this.text,
						fromId: this.userId
					})
					this.text = ''
					this.$nextTick(() => {
						this.scrollToBottom()
					})

				} catch (e) {
					this.$errMessageToast(e)

				}
			},
		},
		mounted() {
			const query = uni.createSelectorQuery().in(this);
			query.select('.middle').boundingClientRect(data => {
				this.scrollViewHeight = Math.floor(data.height)
			}).exec();
		},
		async onLoad(options) {
			const {
				captionId,
				teamId
			} = options
			const originators = decodeURIComponent(options.originators)
			this.sendUser = {
				originators: originators,
				captionId: captionId,
				teamId: teamId,
			}
			uni.setNavigationBarTitle({
				title: originators
			});
			try {
				const data = {
					toId: String(captionId),
					pageNum: 1,
					pageSize: 10
				}
				const result = await this.$mjcrequest.request({
					url: this.$api.getHistory,
					header: this.$aplsjsonheader,
					data: JSON.stringify(data)
				});

				this.list = result

				this.$nextTick(async () => {
					this.scrollToBottom()
					if (!this.$userInfo || this.$userInfo == undefined || this.$userInfo == '' || this
						.$userInfo == null) {
						try {
							const res = await this.$mjcrequest.request({
								url: this.$api.getUser,
								method: 'GET',
								header: this.$aplsjsonheader,
							})
							this.$binduserInfo(res)
							console.log(this.$userInfo, 269);
						} catch (e) {

							this.$errMessageToast(e)
						}
					}
					const userInfo = this.$userInfo
					this.userId = userInfo.id
					this.userName = userInfo.userName
					wx.connectSocket({
						url: 'ws://120.24.52.197:9890/ws/' + userInfo.id, //线上地址
						header: {
							'content-Type': 'application/json'
						},
						// protocols: ['protocol1'],
						//如需本地测试，就使用如下配置，注意是ws协议，不是wss,因为小程序要求使用wss,等同于要求使用https是一个道理，所以本地开发需要使用ws,上线后换成wss

						//url: `ws://本地IP:本地端口号/websocket/` + id, //本地
						success: function() {
							console.log('websocket连接成功~')
						},
						fail: function() {
							console.log('websocket连接失败~')
						},
					})
					wx.onSocketOpen((res) => {
						console.log('连接已经打开');
						console.log(res, 'onSocketOpen');
						wx.onSocketMessage((res) => {
							console.log('服务器对面来的');
							const data = JSON.parse(res.data)
							this.list.push({
								isRight: false,
								msg: data.msg,
								fromId: data.from
							})
							this.$nextTick(() => {
								this.scrollToBottom()
							})
						})
					})
					wx.onSocketClose(function(res) {
						console.log('WebSocket 已关闭！')
					})

				})
			} catch (e) {
				this.$errMessageToast(e)
				//TODO handle the exception

			}
		},
		destroyed() {
			wx.closeSocket()
		},
		async created() {}
	}
</script>

<style lang="less" scoped>
	.commutation {
		height: 100vh;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;


		.quan_icon_emoji {
			width: 50px;
			height: 50px;
		}

		.middle {
			padding: 15rpx;
			flex: 1;
			overflow: auto;

			.scroll-view {
				height: 100%;
			}

			.box {
				margin: 15px 0;
				min-height: 80rpx;

				.right {
					// display: flex;
					// align-items: center;
					// justify-content: flex-end;
					position: relative;
					text-align: right;

					&_text {
						max-width: 450rpx;
						margin-right: 110rpx;
						display: inline-block;
						background-color: #fff;
						border-radius: 15rpx;
						padding: 20rpx 30rpx;
						text-align: left;
						position: relative;

						&::before {
							content: '';
							position: absolute;
							right: 0;
							top: 40rpx;
							transform: translate(60%, -50%);
							width: 0;
							height: 0;
							border-top: 20rpx solid transparent;
							border-bottom: 20rpx solid transparent;
							border-left: 20rpx solid #fff;
						}
					}

					&_image {
						position: absolute;
						display: inline-block;
						width: 80rpx;
						height: 80rpx;
						border-radius: 15rpx;
						overflow: hidden;
						right: 0;

						& image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
				}

				.left {
					// display: flex;
					// align-items: center;
					position: relative;

					&_text {
						max-width: calc(100% - 60px);
						display: inline-block;
						margin-left: 110rpx;
						// min-height: 80rpx;

						background-color: #fff;
						border-radius: 15rpx;
						padding: 20rpx 30rpx;
						text-align: left;
						position: relative;

						&::before {
							content: '';
							position: absolute;
							left: 0;
							top: 40rpx;
							transform: translate(-60%, -50%);
							width: 0;
							height: 0;
							border-top: 20rpx solid transparent;
							border-bottom: 20rpx solid transparent;
							border-right: 20rpx solid #fff;
						}
					}

					&_image {
						position: absolute;
						display: inline-block;
						width: 80rpx;
						height: 80rpx;
						border-radius: 15rpx;
						overflow: hidden;

						& image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
				}
			}

		}

		.bottom {

			width: 100%;

			min-height: 40px;
			box-sizing: border-box;
			z-index: 99;

			&_top {
				padding: 10rpx;

				height: 40px;
				border-top: 1px solid #ccc;
				display: flex;
				align-items: center;

				&_left {
					flex: 1;
					height: 40px;
					background-color: #fff;
					border-radius: 10rpx;
					overflow: hidden;
					display: flex;
					align-items: center;
				}

				&_right {
					width: 100px;

					height: 40px;

					.iconfontbody {
						height: 100%;
						display: flex;
						padding: 0 10px 0 15px;
						align-items: center;
						justify-content: space-between;

						&_xiaolian {
							width: 60rpx;
							height: 60rpx;
						}

						&_send {
							width: 60rpx;
							height: 60rpx;
						}

						& image {
							width: 100%;
							height: 100%;
							object-fit: cover;
						}
					}
				}
			}


		}
	}
</style>
